package com.nioserver.io.task;

import com.helper.Debug;
import com.helper.ProtoJson;
import com.lua.CallLua;
import com.nioserver.io.WorkPool;
import com.nioserver.linklayer.Socket;
import com.nioserver.propertys.Role;
import com.nioserver.propertys.RoleMaps;
import com.proto.TMessage;
import org.luaj.vm2.LuaValue;

import javax.swing.text.html.parser.Parser;
import java.io.IOException;
import java.nio.ByteBuffer;

public class ReadTask implements Runnable {

    Socket socket;
    public ReadTask(Socket socket) {
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            this.socket.read(socket.readBuffer);
            socket.readBuffer.flip();
            byte[] buf = new byte[ socket.readBuffer.remaining()];
            int index = 0;
            while ( socket.readBuffer.remaining()>0){
                buf[index] =  socket.readBuffer.get();
                index++;
            }
            TMessage.Words words = TMessage.Words.parseFrom(buf);
            if(words.toString().equals(""))
                return;
            TMessage.Header header = words.getHeader();
            String  vl = CallLua.getInstance().call(header.getAddress(),header.getFunction(),
                    ProtoJson.Proto2Json(words.getBody()));
            Role rl = RoleMaps.getRole(socket.socketId);
            if(rl!= null){
                Debug.log(words.toString());
                rl.socket.write(ByteBuffer.wrap(ProtoJson.Json2Words(vl).toByteArray()));
            }
            rl.socket.readBuffer.clear();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
